//
//  CLTabBar.swift
//  weibo001
//
//  Created by CL on 16/7/9.
//  Copyright © 2016年 CL. All rights reserved.
//

import UIKit

//定义代理协议

protocol CLTabBarDelegate: NSObjectProtocol {
    
    func didSelectedComposeButton()
}




class CLTabBar: UITabBar {

    weak var clDelegate: CLTabBarDelegate?
    
    
    private lazy var composeButton :UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
         button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
        
    }()
    
    
    @objc private func composeButtonAction() {
        
     clDelegate?.didSelectedComposeButton()
        
        
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
         setupUI()
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
   //添加视图
    private func setupUI() {
      
        addSubview(composeButton)
    }
    
    //调整子控件的frame
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        //设置按钮的宽度
     let itemWidth = width / 5
        
    //记录遍历第几个系统的按钮
       var index = 0
        
        //调整系统控件的位置及大小
        
        for value in subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                index++
                //将要显示搜索按钮的时候多加一个宽度,隔过去中间加按钮
                if index == 2 {
                    index++
                }
            
            }
        }
       
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

}
